import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';

import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import { DataLoadingView } from '../../components/dataLoading';
import { carProgressTotalItem, CarProgressStepItem } from '../../types/myself';
import { getCarProgressStepApi, getUserProgressStepApi, setUserProgressStepStatusApi } from '../../api/myself';

import './index.scss';


const UserProgressPage: React.FC = () => {
  const firstLoadRef = useRef(false);
  const [loading, setLoading] = useState<boolean>(true);
  const carSubject = ['科目一', '科目二', '科目三', '科目四'];
  const tab = Taro.getCurrentInstance().router?.params?.tab || '1';
  const [refreshStatus, setRefreshStatus] = useState<boolean>(false);
  const { carSubjectProcess, setCarSubjectProcess } = useAppContext();

  let tabValue = '科目一';
  try {
    if (tab && Number(tab) > 0 && Number(tab) <= 4) {
      tabValue = carSubject[Number(tab) - 1];
    }
  } catch (error) {
    tabValue = '科目一';
  }
  const [activeKey, setActiveKey] = useState<string>(tabValue);
  const [totalProcess, setTotalProcess] = useState<Record<string, carProgressTotalItem>>({});
  

  const navigateMapping: Record<string, { name: string; hasId: number; special: any }> = {
    "buildStudentRelationship": {name: "user-apply", hasId: 0, special: ''},
    "drivingHospital": {name: "user-drive-hospital", hasId: 1, special: ''},
    "mockTestPass": {name: "user-course", hasId: 1, special: 1},
    "interviewAppointment": {name: "user-interview", hasId: 1, special: 1},
    "studyTimeStandard1": {name: "user-study-time", hasId: 1, special: 1},
    "subjectOneAppointment": {name: "user-subject1-appoint", hasId: 1, special: 1},
    "subjectOnePass": {name: "user-subject-pass", hasId: 1, special: 1},
    "carPractice2": {name: "user-time-appoint", hasId: 0, special: 2},
    "studyTimeStandard2": {name: "user-study-time-standard", hasId: 1, special: 2},
    "subjectTwoAppointment": {name: "user-subject-appointment", hasId: 1, special: 2},
    "subjectTwoPass": {name: "user-subject-pass", hasId: 1, special: 2},
    "carPractice3": {name: "user-time-appoint", hasId: 0, special: 3},
    "studyTimeStandard3": {name: "user-study-time-standard", hasId: 1, special: 3},
    "subjectThreeAppointment": {name: "user-subject-appointment", hasId: 1, special: 3},
    "subjectThreePass": {name: "user-subject-pass", hasId: 1, special: 3},
    "studyTimeStandard4": {name: "user-study-time", hasId: 1, special: 4},
    "mock4TestPass": {name: "user-course", hasId: 1, special: 4},
    "subjectFourAppointment": {name: "user-subject4-appoint", hasId: 1, special: 4},
    "subjectFourPass": {name: "user-subject-pass", hasId: 1, special: 4},
    "GetDriverLicense": {name: "user-car-license", hasId: 1, special: 4}
  };

  const getCarProgress = async () => {
    try {
      setLoading(true);
      setCarSubjectProcess({});
      const [carProgressRes, userProgressRes] = await Promise.all([
        getCarProgressStepApi(),
        getUserProgressStepApi()
      ]);
      
      if (carProgressRes.code === 200 && carProgressRes.data) {
        // 获取基础进度步骤数据
        const baseProgressData = carProgressRes.data;
        
        // 如果用户进度数据存在，合并用户进度状态
        if (userProgressRes.code === 200 && userProgressRes.data && userProgressRes.data.length > 0) {
          const userProgressMap = new Map(userProgressRes.data.map(item => [item.step_id, item]));
          Object.keys(baseProgressData).forEach(subject => {
            baseProgressData[subject].forEach(step => {
              const userProgress = userProgressMap.get(step.id);
              if (userProgress) {
                step.status = userProgress.status;
                step.completed_time = userProgress.created_at || '';
                step.has_child = userProgress.children ? 1 : 0;
                step.children = userProgress.children ? userProgress.children.split(',') : [];
              }
            });
          });
        } 
        setCarSubjectProcess(baseProgressData);
        const processData: Record<string, carProgressTotalItem> = {};
        Object.keys(baseProgressData).forEach(subject => {
          const steps: any = baseProgressData[subject];
          if (steps && steps.length > 0) {
            const completed = steps.filter(s => s.status === 1).length;
            processData[subject] = {
              'completed': completed,
              'total': steps.length,
              'percent': Math.floor((completed / steps.length) * 100)
            };
          } else {
            processData[subject] = {
              'completed': 0,
              'total': steps.length,
              'percent': 0
            };
          }
        });
        setTotalProcess(processData);
      }
    } catch (err) {
      console.log(err);
      Taro.showToast({ title: '获取进度数据失败', icon: 'none' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    console.log('useEffect getCarProgress:', firstLoadRef.current);
    if (!firstLoadRef.current){
      firstLoadRef.current = true;
      getCarProgress();
    }    
  }, []);

  // 处理标签页切换
  const handleTabChange = (key: string) => {
    setActiveKey(key);
  };

  // 处理步骤点击
  const handleStepClick = (step: CarProgressStepItem) => {
    const key: string = step.guide;
    const data = navigateMapping[key];
    if (data) {
      let params = ''
      if (data.hasId === 1) {
        params = `?stepId=${step.id}`
      }
      if (data.special) {
        params = params?`${params}&tab=${data.special}`:`?tab=${data.special}`
      }
      Taro.navigateTo({ url: `/pages/${data.name}/index${params}`});
    }
  };

  // 更新步骤状态
  const updateStepStatus = async (stepId: number, e: any) => {
    e.stopPropagation();
    try {
      // 调用API更新步骤状态
      const res = await setUserProgressStepStatusApi(stepId, 1);
      if (res.code === 200) {
          Taro.showToast({ title: '操作成功~', icon: 'success' });
          // 更新本地状态
          setCarSubjectProcess(prev => {
            if (!prev) return null;
            const updatedData = { ...prev };
            Object.keys(updatedData).forEach(subject => {
              const steps = updatedData[subject];
              if (steps) {
                steps.forEach(step => {
                  if (step.id === stepId) {
                    step.status = 1;
                    step.has_child = 1;
                    step.completed_time = res.data.created_at;
                  }
                });
              }
            });
            return updatedData;
          });
          
          // 重新计算进度
          if (carSubjectProcess) {
            const processData: Record<string, number> = {};
            Object.keys(carSubjectProcess).forEach(subject => {
              const steps = carSubjectProcess[subject];
              if (steps && steps.length > 0) {
                const completed = steps.filter(s => s.status === 1).length;
                processData[subject] = Math.floor((completed / steps.length) * 100);
              } else {
                processData[subject] = 0;
              }
            });
            setTotalProcess(processData);
          }
      } else {
        Taro.showToast({ title: '操作失败，请稍后重试~', icon: 'none' });
      }
    } catch (error) {
      console.error('更新步骤状态失败:', error);
      Taro.showToast({ title: '操作失败，请稍后重试~', icon: 'none' });
    }
  };

  const refreshData = async () => {
    setRefreshStatus(true);
    await getCarProgress();
    Taro.stopPullDownRefresh();
    setRefreshStatus(false);
  }

  return (
    <View className="page-container user-progress-container">
      <PageHeader title="我的学车进度" />
      {/* 科目标签页 */}
      <View className="custom-tabs">
        <View className="tabs-header">
          {carSubject.map((subject) => (
            <View
              key={subject}
              className={`tabs-tab ${activeKey === subject ? 'tabs-tab-active' : ''}`}
              onClick={() => handleTabChange(subject)}
            >
              <Text>{subject}</Text>
            </View>
          ))}
        </View>
        
        {/* 标签页内容 */}
        <View className="tabs-content">
          {carSubjectProcess ? (
            <>
              {/* 进度条 */}
              <View className="progress-container">
                <View>
                  <Text className="progress-step-title">{activeKey}进度</Text>
                  {/* 进度条 */}
                  <View className="progress-bar-container">
                    <View
                      className="progress-bar"
                      style={{ width: `${totalProcess[activeKey]?.percent}%` }}
                    />
                    <Text className="progress-text">
                      {totalProcess[activeKey]?.percent || 0}%
                    </Text>
                    <View
                      className="progress-car-icon"
                      style={{ left: `${totalProcess[activeKey]?.completed?totalProcess[activeKey]?.percent == 100?40:totalProcess[activeKey]?.percent:40}%` }}
                    >
                      <MaterialIcons name="directions_car" style={{color: '#000'}} size={20} />
                    </View>
                  </View>
                </View>
                <View className="progress">
                  <View 
                    className="progress-bar"
                    style={{
                      width: `${totalProcess[activeKey]?.percent || 0}%`,
                      backgroundColor: (totalProcess[activeKey]?.percent || 0 > 0) ? (totalProcess[activeKey]?.percent  === 100)?'#00e500': '#30dff3': '#2edfa3'
                    }}
                  />
                </View>
              </View>

              {/* 流程步骤列表 */}
              <ScrollView className="process-steps-list" 
                scrollY refresherEnabled 
                onRefresherRefresh={refreshData}
                refresherTriggered={refreshStatus}
              >
                {carSubjectProcess && activeKey in carSubjectProcess ? 
                  carSubjectProcess[activeKey].map((step: CarProgressStepItem, index: number) => (
                    <View 
                      key={index} 
                      onClick={() => handleStepClick(step)} 
                      className={`process-step-card ${step.status === 1 ? 'completed' : step.status === 2 ? 'processing' : 'pending'}`}
                    >
                      <View className="process-step-content">
                        <View className={`process-step-number ${step.status === 1 ? 'process-step-number-completed' : 
                          step.status === 2 ? 'process-step-number-processing' : 'process-step-number-pending'}`}>
                          {step.step}
                        </View>
                        <View className="process-step-icon ml-2 mr-2">
                          {step.status === 1 ? (
                            <MaterialIcons name="check-circle" color="#53cc85" size={20} />
                          ) : step.status === 2 ? (
                            <MaterialIcons name="access-time" color="#ffc107" size={20} />
                          ) : (
                            <MaterialIcons name="cancel" color="#999" size={20} />
                          )}
                        </View>
                        <View className="process-step-info">
                          <View className="process-step-title">{step.name}</View>
                          {step.completed_time ? (
                            <Text className="process-step-completed-time">
                              {step.completed_time}
                            </Text>
                          ) : null}
                        </View>
                        <View className="process-step-actions">
                          {step.has_child === 0 && !(step.completed_time && step.status == 1) && (
                            <View 
                              className="process-step-complete-action"
                              onClick={(e) => updateStepStatus(step.id, e)}
                            >
                              完成
                            </View>
                          )}
                          <View className="process-step-detail" onClick={() => handleStepClick(step)}>
                            点击查看详情
                          </View>
                        </View>
                      </View>
                    </View>
                  )) : (
                    <View className="text-center">暂无数据</View>
                  )
                }
              </ScrollView>
            </>
          ) : (
            <DataLoadingView />
          )}
        </View>
      </View>
    </View>
  );
};

export default UserProgressPage;
